<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./layui.css">
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .layui-card {
            width: 1024px;
            margin: auto;
        }

        .box {
            height: 24px;
            width: 100%;
            padding: 0;
            margin: 0;
        }

        .good-result {
            width: 50%;
            background-color: green;
            float: left;
        }

        .down-result {
            width: 50%;
            background-color: red;
            float: left;
        }
    </style>
</head>

<body>
    <div class="layui-card">
        <div class="layui-card-header">投票结果</div>
        <div class="layui-card-body">
            <div class="box">
                <div class="good-result">50%</div>
                <div class="down-result">50%</div>
            </div>
            <br>
            <div class="btn">
                <button type="button" class="layui-btn good-btn">赞成</button>
                <button type="button" class="layui-btn down-btn">反对</button>
            </div>

            <div>
                <p>赞成：<strong class="good-number">0</strong></p>
            </div>
            <div>
                <p>反对：<strong class="down-number">0</strong></p>
            </div>
        </div>
    </div>
</body>
<script>
    //赞成按钮  
    let goodBtn = document.querySelector(".good-btn");
    // 反对按钮
    let downBtn = document.querySelector(".down-btn");
    //赞成标签
    let goodP = document.querySelector(".good-number");
    //反对标签
    let downP = document.querySelector(".down-number");
    //赞成数据条
    let goodRes = document.querySelector(".good-result")
    //反对数据条
    let downRes = document.querySelector(".down-result")
    //获取数据条总宽度
    let boxWidth = document.querySelector(".box").clientWidth

    //写入p标签的值初始化
    let num1 = 0;
    let num2 = 0;
    
    //给两个按钮添加监听事件
    document.querySelector(".btn").addEventListener("click", function (e) {
        //赞成按钮
        if (e.target.className == "layui-btn good-btn") {
            // console.log(1111)
            num1++;
            //数字写入p中
            goodP.innerHTML = num1;

        }
        //反对按钮
        else if (e.target.className == "layui-btn down-btn") {
            // console.log(2222)
            num2++
            //数字写入p中
            downP.innerHTML = num2;

        }
        //结果百分比写入数据条
        goodRes.innerHTML = (parseInt(num1 / (num1 + num2) * 10000) / 100) + "%"
        downRes.innerHTML = (parseInt(num2 / (num1 + num2) * 10000) / 100) + "%"
        //根据百分比改变数据条颜色
        goodRes.style.width = (num1 / (num1 + num2)) * boxWidth + "px"
        downRes.style.width = (num2 / (num1 + num2)) * boxWidth + "px"

    })

</script>

</html>